package com.mr.sell.controller;

import com.lly835.bestpay.model.PayResponse;
import com.mr.sell.entity.OrderMaster;
import com.mr.sell.exception.CustomException;
import com.mr.sell.service.OrderService;
import com.mr.sell.service.PayService;
import com.mr.sell.utils.ConstantEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * Class: PayController
 * User (作者):MRui
 * TODO (描述)：微信支付controlle
 * Date 2018.09.25 22:37
 */
@Controller
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayService payService;

    @Autowired
    private OrderService orderService;
    /**
    * User (作者): MRui
    * TODO (描述)：创建支付
    * Data：2018.09.25 22:46
    */
    @GetMapping("/create")
    public ModelAndView create(@RequestParam("orderId") String orderId,
                               @RequestParam("returnUrl") String returnUrl,
                               Map<String,Object> map){
        //1.查询订单
        OrderMaster orderMaster = orderService.getOrder(orderId);
        if (orderMaster == null){
            throw new CustomException(ConstantEnum.EXCEPTION_ORDER_NOT_EXIST);
        }
        //2.发起支付
        PayResponse payResponse = payService.create(orderMaster);
        map.put("payResponse",payResponse);
        map.put("returnUrl",returnUrl);
        return new ModelAndView("pay/create");
    }

    /**
    * User (作者): MRui
    * TODO (描述)：微信异步通知
    * Data：2018.09.26 23:49
    */
    @PostMapping("/notify")
    public ModelAndView notify(@RequestParam("notifyData") String notifyData){
        payService.notify(notifyData);
        //返回给微信处理结果
        return new ModelAndView("pay/success");
    }
}
